package com.schoolegard.services.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.schoolegard.services.TerminalService;
import com.schoolgard.dao.CardLogToDeviceDao;
import com.schoolgard.dao.ParamAccessDao;
import com.schoolgard.dao.ParamCameraDao;
import com.schoolgard.dao.TerminalDao;
import com.schoolgard.entitybean.CardLogToDevice;
import com.schoolgard.entitybean.ParamAccess;
import com.schoolgard.entitybean.ParamCamera;
import com.schoolgard.entitybean.Terminal;

public class TerminalServiceImpl implements TerminalService {
	
	private static Logger logger = Logger.getLogger(TerminalServiceImpl.class);
	
	private TerminalDao terminalDao;
	private ParamCameraDao paramCameraDao; 
	private ParamAccessDao paramAccessDao;
	private CardLogToDeviceDao cardLogToDeviceDao;
	public void setTerminalDao(TerminalDao terminalDao) {
		this.terminalDao = terminalDao;
	}
	public void setParamCameraDao(ParamCameraDao paramCameraDao) {
		this.paramCameraDao = paramCameraDao;
	}
	public void setParamAccessDao(ParamAccessDao paramAccessDao) {
		this.paramAccessDao = paramAccessDao;
	}
	public void setCardLogToDeviceDao(CardLogToDeviceDao cardLogToDeviceDao) {
		this.cardLogToDeviceDao = cardLogToDeviceDao;
	}
	@Override
	public List<Terminal> findByDevice(String deviceId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Terminal.class);
		criteria.add(Restrictions.eq("device.guid", deviceId));
		return terminalDao.findByCriteria(criteria);
	}
	@Override
	public Terminal findById(String terminalId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Terminal.class);
		criteria.add(Restrictions.eq("guid", terminalId));
		List<Terminal> terminal = terminalDao.findByCriteria(criteria);
		return (terminal != null && terminal.size() > 0)?terminal.get(0):null;
	}
	@Override
	public void saveOrUpdate(Terminal terminal) {
        terminalDao.createOrModify(terminal);		
	}
	@Override
	public void delete(String guid) { //TODO 如此判断类型不合适
		Terminal ter = findById(guid);
		if(ter.getHdType().getName().indexOf("摄像") != -1){
			ParamCamera pc = paramCameraDao.findById(guid);
			if(pc != null) {
				paramCameraDao.remove(pc);
			}
		}else if(ter.getHdType().getName().indexOf("刷卡") != -1){
			ParamAccess parma = paramAccessDao.findById(guid);
			if(parma != null)
				paramAccessDao.remove(parma);
		}
		DetachedCriteria criteria = DetachedCriteria.forClass(CardLogToDevice.class);
		criteria.add(Restrictions.eq("guid", guid));
		List<CardLogToDevice> clds = cardLogToDeviceDao.findByCriteria(criteria);
		if(clds != null && clds.size() > 0) {
			cardLogToDeviceDao.remove(clds);
		}
        terminalDao.remove(ter);		
	}
	

}
